package com.common.basic.base;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.context.MessageSource;
import org.springframework.web.servlet.support.JspAwareRequestContext;
import org.springframework.web.servlet.support.RequestContext;

import com.common.basic.util.Globals;

public abstract class BaseTaglib extends TagSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 3870541710354622403L;
	
	private RequestContext requestContext;
	
	public int doStartTag() throws JspException {
		requestContext = (RequestContext)pageContext.getAttribute(Globals.CONTEXT_KEY);
        try
        {
            if(requestContext == null)
            {
                requestContext = new JspAwareRequestContext(pageContext);
                pageContext.setAttribute(Globals.CONTEXT_KEY, requestContext);
            }
            return super.doStartTag();
        }
        catch(JspException ex)
        {
            throw ex;
        }
        catch(RuntimeException ex)
        {
            throw ex;
        }
        catch(Exception ex)
        {
            throw new JspTagException(ex.getMessage());
        }		
	}
	
	protected final RequestContext getRequestContext()
    {
        return requestContext;
    }
	
	protected String getMessage(String code, Object[] args, Locale locale)
    {
		MessageSource messageSource = getRequestContext().getMessageSource();
		if(messageSource==null)
			return code;
		return messageSource.getMessage(code, args, locale);
    }
	
	protected void write(PageContext pageContext, String text)throws JspException 
    {
        JspWriter writer = pageContext.getOut();
        try
        {
            writer.print(text);
        }
        catch(IOException e)
        {
            throw new JspException(e+"");
        }
        finally
        {
            writer = null;
        }
    }
}
